﻿using System.Collections.Generic;

namespace NodeEditor
{
    public static class TreeHelper
    {
        public static T[] ForEach<T>(this T start)where T :INode
        {
            Dictionary<T, bool> visited = new Dictionary<T, bool>();
            Queue<T> queue = new Queue<T>();
            List<T> nodes = new List<T>();
            queue.Enqueue(start);
            visited.Add(start, false);
            while (queue.Count > 0)
            {
                var _ = queue.Dequeue();
                int count = 0;
                foreach (T __ in _.GetLefts())
                {
                    if (!visited.ContainsKey(__))
                    {
                        count++;
                        queue.Enqueue(__);
                        visited.Add(__, false);
                    }
                }
                if (visited.ContainsKey(_) && count == 0)
                {
                    if(!visited[_])
                    {
                        visited[_] = true;
                        nodes.Add(_);
                    }
                    foreach (T __ in _.GetRights())
                    {
                        queue.Enqueue(__);
                        if (!visited.ContainsKey(__))
                        {
                            visited.Add(__, false);
                        }
                    }
                }
            }
            return nodes.ToArray();
        }
    }
}